<template>
  <d2-container>
    <t-table
      :data="data"
      :columns="columns"
      :rowKey="data.id"
      :verticalAlign="verticalAlign"
      :loading="isLoading"
      :pagination="pagination"
      @change="rehandleChange"
      :expanded-row-keys="expandedRowKeys"
      :expanded-row="expandedRow"
      @expand-change="rehandleExpandChange"
      :expandOnRowClick="expandOnRowClick"
      :filter-value="filterValue"
      @filter-change="onFilterChange"
      :expandIcon="expandIcon"
    >
      <template #op="slotProps">
        <!-- ="slotProps" -->
        <!-- <a class="link" @click="rehandleClickOp(slotProps)">管理</a>
        <a class="link" @click="rehandleClickOp(slotProps)">删除</a> -->
        <t-button theme="success" @click="expandList(slotProps)">
          <UserIcon slot="icon" />
          管理
        </t-button>
      </template>
    </t-table>

    <!-- data:数据源
    columns:列配置
    rowKey：行唯一标识
    verticalAlign：行内容上下方向对齐
    loading：加载中状态
    pagination：分页配置
    change：分页、排序、过滤等内容变化时触发，泛型 T 指表格数据类型
    bordered：是否显示表格边框
    stripe：是否显示斑马纹
    expandedRowKeys：展开行
    expandedRow：展开行内容
    @expand-change：展开行发生变化时触发
   :expandOnRowClick：是否允许点击行展开
     -->
  </d2-container>
</template>

<script>
import { UserIcon } from 'tdesign-icons-vue'
import { MessagePlugin } from 'tdesign-vue'
import util from '@/libs/util.js'

export default {
  components: {
    UserIcon
  },
  data() {
    return {
      data: [],
      isLoading: false,
      filterValue: {},
      expandOnRowClick: false,
      expandIcon: false,
      // 有哪些 data.id 在 expandedRowKeys 中，就显示这些 id 对应的行
      expandedRowKeys: [],
      // 展开行的内容
      // default-value="3"
      expandedRow: (h, { row }) => (
        <t-form>
          <t-form-item label="管理权限" name="status">
            <t-switch v-model={row.isAdmin}></t-switch>
          </t-form-item>
          <t-form-item label="车牌号码" name="tel">
            <t-input
              placeholder="请输入内容"
              v-model={row.editNumber}
            ></t-input>
          </t-form-item>
          <t-form-item label="邮箱号码" name="tel">
            <t-input placeholder="请输入内容" v-model={row.editMail}></t-input>
          </t-form-item>
          <t-form-item label="修改密码" name="tel">
            <t-input
              placeholder="请输入内容,无输入则不改动"
              v-model={row.password}
            ></t-input>
          </t-form-item>
          <t-form-item>
            <t-button onClick={() => this.edit(row)}>修改</t-button>
          </t-form-item>
        </t-form>
      ),
      columns: [
        {
          width: 100,
          colKey: 'id',
          title: 'id'
        },
        {
          width: 200,
          colKey: 'username',
          title: '用户名',
          filter: {
            type: 'input',
            resetValue: '',
            props: {
              placeholder: '输入关键词过滤',
              clearable: true
            },
            // 是否显示重置取消按钮
            showConfirmAndReset: true
          }
        },
        {
          width: 200,
          colKey: 'permission',
          title: '权限',
          filter: {
            type: 'single',
            // showConfirmAndReset: true,
            list: [
              { label: 'SUPER_ADMIN', value: 'SUPER_ADMIN' },
              { label: 'ADMIN', value: 'ADMIN' },
              { label: 'USER', value: 'USER' }
            ]
          }
          // render(h, { row: { phone } }) {
          //   return phone;
          // },
        },
        {
          width: 200,
          colKey: 'carId',
          title: '车牌',
          filter: {
            type: 'input',
            resetValue: '',
            props: {
              placeholder: '输入关键词过滤',
              clearable: true
            },
            // 是否显示重置取消按钮
            showConfirmAndReset: true
          }
        },
        {
          width: 200,
          colKey: 'mail',
          title: '邮箱',
          filter: {
            type: 'input',
            resetValue: '',
            props: {
              placeholder: '输入关键词过滤',
              clearable: true
            },
            // 是否显示重置取消按钮
            showConfirmAndReset: true
          }
        },
        {
          width: 200,
          colKey: 'operate',
          title: '操作',
          cell: 'op',
          align: 'center'
        }
      ],
      // rowKey: "property",
      tableLayout: 'auto',
      verticalAlign: 'top',
      rowClassName: 'property-class',
      pagination: {
        current: 1,
        pageSize: 10
      }
    }
  },
  async mounted() {
    await this.fetchData(this.pagination)
  },
  methods: {
    async fetchData(pagination = this.pagination) {
      try {
        this.isLoading = true
        const { current, pageSize } = pagination
        const response = await fetch('/api/user/getUserList', {
          body: JSON.stringify({
            page: current,
            amount: pageSize
          }),
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer${util.cookies.get('token')}`
          }
        }).then((x) => x.json())
        // console.log('response', response)
        this.data = response.obj.list
        // console.log(this)
        for (var i = 0; i < this.data.length; i++) {
          this.data[i].isAdmin = this.data[i].permission !== 'USER'
          this.data[i].editMail = this.data[i].mail
          this.data[i].editNumber = this.data[i].number
          this.data[i].password = null
        }
        this.data = JSON.parse(JSON.stringify(this.data))

        // console.log(this.data)
        this.pagination = {
          ...pagination,
          total: response.obj.count
        }
        // console.log('分页数据', response.obj.list)
      } catch (err) {
        // console.log(err)
        this.data = []
      }
      this.isLoading = false
    },
    // 也可以使用 page-change 事件
    async rehandleChange(changeParams, triggerAndData) {
      console.log(
        '分页、排序、过滤等发生变化时会触发 change 事件：',
        changeParams,
        triggerAndData
      )
      if (changeParams.pagination === undefined) return
      const { current, pageSize } = changeParams.pagination
      const pagination = { current, pageSize }
      await this.fetchData(pagination)
    },
    //
    rehandleClickOp({ text, row }) {
      // console.log(text, row)
    },
    rehandleSelectChange(value, { selectedRowData }) {
      this.selectedRowKeys = value
      // console.log(value, selectedRowData)
    },
    // 具体展开哪一行
    rehandleExpandChange(value, { expandedRowData }) {
      this.expandedRowKeys = value
      // console.log('rehandleExpandChange', value, expandedRowData)
    },
    async edit(data) {
      // console.log(data)
       const token = this.$store.state.d2admin.user.token
      const response = await fetch('/api/user/editUser', {
        body: JSON.stringify({
          id: data.id,
          password: data.password,
          number: data.editNumber,
          mail: data.editMail,
          permission: data.isAdmin
        }),
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
             Authorization:
           `Bearer${token}`
        }
      }).then((x) => x.json())
      MessagePlugin(response.code === 200 ? 'success' : 'error', {
        content: response.message,
        duration: 2000
      })
      this.fetchData(this.pagination)
      // .then((x) => x.json());
      // console.log("response", response);
      // this.data = response.obj.list;
    },
    onFilterChange(filters) {
      this.filterValue = filters
      // 模拟异步请求进行数据过滤
      this.request(this.filterValue)
    },
    async request(filters) {
       const token = this.$store.state.d2admin.user.token
      const response = await fetch('/api/user/filter', {
        body: JSON.stringify(filters),
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization:
           `Bearer${token}`
        }
      }).then((x) => x.json())
      // console.log('response', response)
      this.data = response.obj
      this.pagination.total = this.data.length
    },
    expandList({ row }) {
      // console.log(row.id)
      if (this.expandedRowKeys[0] === row.id) this.expandedRowKeys = []
      else this.expandedRowKeys = [row.id]
    }
  }
}
</script>
